﻿module Sustainalytics.News {

    import Common = Sustainalytics.Common;

    export class NewsService implements INewsService {

        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private notificationFactory: INotificationFactory;
        private staticObjects: IStaticObjects;

        // Ctor.
        constructor($q: ng.IQService, $http: ng.IHttpService, notificationFactory: INotificationFactory, staticObjects: IStaticObjects) {
            this.$q = $q;
            this.$http = $http;
            this.notificationFactory = notificationFactory;
            this.staticObjects = staticObjects;
        }

        // show error message for a given error code
        private showError(err) {
            var ctx = this;
            if (err && err['errorCode'])
                ctx.notificationFactory.error('', ctx.staticObjects.getMessageByInternalCode(err['errorCode']));
        }

        // add one news
        public addNews(news: NewsDto): ng.IPromise<NewsDto> {
            var ctx = this;
            var def = this.$q.defer();
            var url: string = '/newsserv/api/v1/news';
            var promise: ng.IHttpPromise<NewsDto> = this.$http.post(url, news);
            promise.success(function (data) { def.resolve(data); }).error(function (err) { ctx.showError(err); def.reject(); })
            return def.promise;
        }

        // delete one news
        public deleteNews(id: string): ng.IPromise<Object> {
            var ctx = this;
            var def = this.$q.defer();
            var url: string = '/newsserv/api/v1/news/' + id;
            var promise: ng.IHttpPromise<{}> = this.$http.delete(url);
            promise.success(function (data) { def.resolve(data); }).error(function (err) { ctx.showError(err); def.reject(); })
            return def.promise;
        }

        // delete multiple news
        public deleteMultipleNews(newsItems: string[]): ng.IPromise<Object> {
            var ctx = this;
            var def = this.$q.defer();

            var deletePromises = new Array();

            // for each item call delete
            $(newsItems).each(function () {
                var id = this;
                var promise = ctx.deleteNews(id);
                deletePromises.push(promise);
            });

            var allPromise = this.$q.all(deletePromises);
            return allPromise;
        }

        // get one news
        public getNews(newsId: string): ng.IPromise<NewsDto> {
            var ctx = this;
            var def = this.$q.defer();

            var query =
                {
                    //use account to filter the news depending on the RelationshipType of the account
                    accountId: null,
                    fromAdmin: true
                };

            var url = '/newsserv/api/v1/news/' + newsId + '?' + $.param(query);
            var promise = this.$http.get(url);
            promise.success(function (data) { def.resolve(data); }).error(function (err) { ctx.showError(err); def.reject(); })
            return def.promise;
        }

        // get filtered list of news
        public getNewsFilteredWithOptions(filter: NewsFilter, listOptions: Common.ListOptions): ng.IPromise<any> {
            var ctx = this;
            var def = this.$q.defer();

            var query =
                {
                    term: filter.term,
                    category: filter.category,
                    isPublished: false,
                    availableFilter: 1, //the user can see all the news (1 - All, 2 - Client, 3 - Prospect)
                    //use account to filter the news depending on the RelationshipType of the account
                    accountId: null,
                    listOptions: listOptions,
                    fromAdmin: true
                };

            var url = '/newsserv/api/v1/news?' + $.param(query);
            var promise = this.$http.get(url);
            promise
                .success(function (data)
                {
                    def.resolve(data);
                }).error(function (err)
                {
                    ctx.showError(err);
                    console.log(err);
                    def.reject();
                })
            return def.promise;
        }

        // get list of news
        public getNewsFiltered(filter: NewsFilter, skip: number, take: number, orderBy: string[], orderByAsc: boolean): ng.IPromise<NewsDto[]> {
            var ctx = this;

            var options = new Common.ListOptions();
            options.skip = skip;
            options.take = take;
            options.orderBy = orderBy;
            options.orderAscending = orderByAsc;
            options.includeAllFields = true;

            var promise = ctx.getNewsFilteredWithOptions(filter, options);

            return promise;
        }

        // get number of news
        public getNewsCount(filter: NewsFilter): ng.IPromise<number> {
            var ctx = this;

            var options = new Common.ListOptions();
            options.getCount = true;

            var promise = ctx.getNewsFilteredWithOptions(filter, options);

            return promise;
        }

        // get news paged
        public getNewsPaged(filter: NewsFilter, skip: number, take: number, orderBy: string[], orderByAsc: boolean): ng.IPromise<Common.PagedList<NewsDto>> {
            var ctx = this;
            var itemsPromise = ctx.getNewsFiltered(filter, skip, take, orderBy, orderByAsc);
            var totalItemsCountPromise = ctx.getNewsCount(filter);

            var pagedListPromise = Common.PagedList.createPagedListFromPromises(ctx.$q, itemsPromise, skip, take, totalItemsCountPromise);

            return pagedListPromise;
        }

        // update news
        public updateNews(news: NewsDto): ng.IPromise<NewsDto> {
            var ctx = this;
            var def = this.$q.defer();
            var url = '/newsserv/api/v1/news';
            var promise = this.$http.put(url, news);
            promise.success(function (data) { def.resolve(data); }).error(function (err) { ctx.showError(err); def.reject(); })
            return def.promise;
        }

        // patch news - batch operations to be performed on News => HTTP PATCH
        patchNews(patchData: NewsPatch): ng.IPromise<{}> {
            var ctx = this;
            var def = this.$q.defer();
            var url = '/newsserv/api/v1/news';
            var httpConfig: ng.IRequestConfig = { method: 'PATCH', url: url, data: patchData };
            var promise = this.$http(httpConfig);
            promise.success(function (data) { def.resolve(data); }).error(function (err) { ctx.showError(err); def.reject(); })
            return def.promise;
        }
    }

// register service with News Angular module
angular.module('Sustainalytics.News').factory('NewsService', function ($q: ng.IQService, $http: ng.IHttpService, notificationFactory: INotificationFactory, staticObjects: IStaticObjects) {
        var srv = new NewsService($q, $http, notificationFactory, staticObjects);
        return srv;
    });
} 